﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using SimpleTools;

namespace SimpleTools.Json
{
    public static class SJsonTool
    {
        #region 静态方法
        /// <summary>
        /// 把JSON字段转换成对象
        /// </summary>
        /// <param name="json">该类型的json字符串</param>
        /// <returns>JsonData对象</returns>
        public static JsonData GetJsonData(string json)
        {
            return JsonConvert.DeserializeObject<JsonData>(json);
        }

        /// <summary>
        /// 把JSON字段转换成对象并判断字段中是否有指定的键
        /// </summary>
        /// <param name="json">该类型的json字符串</param>
        /// <param name="keys">键，不定个数</param>
        /// <returns>JsonData对象,如果不含有键则返回空对象</returns>
        public static JsonData GetJsonData(string json,bool needToken ,params string[] keys)
        {
            var data = JsonConvert.DeserializeObject<JsonData>(json);
            if (
                data == null||//转换失败
                (needToken && !data.IsContainKey("token"))||//没有要求的token字段
                !data.IsContainKeys(keys)//没有要求的其他字段
                )
            {
                return null;
            }
            else return data;
        }

        /// <summary>
        /// 获取成功Json
        /// </summary>
        /// <param name="reason"></param>
        /// <returns></returns>
        public static JsonData GetSucJson(params string[] strs)
        {
            JsonData back = new JsonData("suc");
            for (int i = 0; i < strs.Length; i += 2)
            {
                back.Add(strs[i], strs[i + 1]);
            }
            return back;
        }

        /// <summary>
        /// 获取失败Json
        /// </summary>
        /// <param name="reason"></param>
        /// <returns></returns>
        public static JsonData GetBadJson(string reason)
        {
            JsonData back = new JsonData("bad");
            back.Add("reason", reason);
            return back;
        }

        /// <summary>
        /// 获取成功字符串
        /// </summary>
        /// <param name="reason"></param>
        /// <returns></returns>
        public static string GetSucJsonStr(params string[] strs)
        {
            JsonData back = new JsonData("suc");
            for (int i = 0; i < strs.Length; i += 2)
            {
                back.Add(strs[i], strs[i + 1]);
            }
            return back.Json;
        }

        /// <summary>
        /// 获取失败json字符串
        /// </summary>
        /// <param name="reason">失败原因</param>
        /// <returns>返回 [action:bad,reason:原因] 的失败json字符串</returns>
        public static string GetBadJsonStr(string reason)
        {
            JsonData back = new JsonData("bad");
            back.Add("reason", reason);
            return back.Json;
        }
        #endregion
    }
}
